<?php if(!defined('THINK_PATH')) exit('Access Denied');
class CronAction extends SakuraAction {
    public function __construct(){
    	parent::__construct();
    }
    public function InitCron(){
    	$last = A('Cache')->GetCache('cronLast');
    	$now = date('d');
    	if(($now < $last ? $now + $last : $now) - $last >= 1){
    		A('Cache')->SetCache('cronLast',$now);
    		$this->EveryDay();
    	}
    }
    public function EveryDay(){
    	/*
    	$fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);
		if($fp){
			$out = "GET ".$_SERVER['SCRIPT_NAME'].U('Cron/execute')." HTTP/1.1\r\n";
			$out .= "Host: ".$_SERVER['HTTP_HOST']."\r\n";
			$out .= "Connection: Close\r\n\r\n";
			fwrite($fp,$out);
			usleep(5);
			fclose($fp);
		}
		*/
    	$this->execute();
    }
    public function execute(){
    	set_time_limit(3600);
    	A('Cache')->SetCache('cronLastExecute',time());
    	$sevenDays = 3600*24*7;
    	
		$time = time()-$sevenDays;
		$where = array();
		$where['timestamp'] = array('lt',$time);
		$where['status'] = array('eq','1');
		$where['_logic'] = 'AND';
		M('Orders')->where($where)->delete();

		$time = date('Ymd',time()+$sevenDays);
		$where = array();
		$where['exptime'] = array('lt',$time);
		$expi_list = M('Hostings')->where($where)->select();
		$sendlist = array();
		if($expi_list){
			foreach($expi_list as $v){
				if($v['exptime'] >= date("Ymd")){
					$sendlist[] = array('panelusername'=>$v['panelusername'],'email'=>$v['email']);
					A('Cache')->SetCache('cronHostingLastExecute',mktime());
				}
			}
		}
		if($sendlist){
			foreach($sendlist as $val){
				$post = array();
				$post['email'] = $val['email'];
				$post['title'] = '您的主机即将过期请续费';
				$post['context'] = '<p>尊敬的客户：</p><p>您的主机'.$val['panelusername'].'即将到期，请及时续费！</p>';
				MailAction::SendMail($post['email'],$post['title'],$post['context']);
			}
		}
		
		$time = date('Ymd',time()-$sevenDays);
		$where = array();
		$where['exptime'] = array('lt',$time);
		M('Hostings')->where($where)->delete();
    }
}